<?php
/**
*
* 功能描述（接口控制器）
*
* @author suoya <jlusuoya@gmail.com>
* @version 1
*/

class CtrlApi extends CtrlBase
{
	public $paramCheck = array(
		'zfbnotify' => array(
			'id' => array('GET', 'must', 'trim', 'notempty'),
			'oid' => array('GET', 'must', 'trim', 'notempty'),
			'status' => array('GET', 'must', 'trim', 'notempty'),
			'amount' => array('GET', 'must', 'floatval', 'positive'),
		),
	);
	public $perm = array('allow', '');

	function ZfbNotify()
	{
		$id = GetDataId($this->params['id']);
		$obj = $this->GetModel('trade');
		$data = $obj->GetItem($id);
		if(!$data)
			return RT_ATTACK;
		$newSta = $this->params['status'];		//支付宝返回状态
		if($data['status'] != 1)
		{
		   	if($data['ret_status'] != $newSta)		//即不是首次发送，又不是重复状态，认为非法
				return RT_ATTACK;
			else
			{
				echo "1";
				return RT_NONE;
			}
		}
    	$succ = ($newSta == 'TRADE_FINISHED' || $newSta == 'TRADE_SUCCESS');
		$info = array(
			'status' => $succ ? 2 : 3,
			'lasttime' => date('Y-m-d H:i:s'),
			'order_id' => $this->params['oid'],
			'ret_status' => $newSta,
		);
		$cnt = $obj->UpdateItem($id, $info);
		$ret = "1";
		if($succ)		//成功处理
		{
			if($this->params['amount'] != $data['amount'])
				$ret = AMOUNT_DIFF;
			else
			{
				//处理
				switch(intval($data['trade_type']))
				{
				case 1: $ret = $this->Charge($data); break;
				case 2: $ret = $this->PayOrder($data); break;
				}
			}
		}
		if($ret !== '1')
			$obj->SetError($data['id'], $ret);
		echo $ret;
		return RT_NONE;
	}

	private function Charge($data)
	{
		$ret = '1';
		$uobj = $this->GetModel('user');
		$cnt = $uobj->AddAmount($data['user_id'], $this->GetCharge($data['amount']));
		if($cnt == 0)
			$ret = USER_NEXIST;
		return $ret;
	}

	//计算充值金额
	private function GetCharge($amount)
	{
		$unit = $amount % 500;
		return $amount + $unit * 100;
	}

	private function PayOrder($data)
	{
		$ret = '1';
		$obj = $this->GetModel('order');
		$od = $obj->GetBaseInfo($data['data_id']);
		if(!$od)
			return ORDER_NEXIST;
		$obj->UpdateOrder(array('pay_adm'=>1), $data['data_id']);
		return $ret;
	}
}

